package top.blackr.folivora.common.security;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.redis.cache.MicaRedisCache;
import org.springframework.web.servlet.HandlerInterceptor;
import top.blackr.folivora.common.core.constants.RedisConstants;
import top.blackr.folivora.common.security.auth.SecUser;
import top.blackr.folivora.common.security.auth.SecurityUtils;


/**
 * 当前登陆用户拦截器
 *
 * @author BlackR
 */
@AllArgsConstructor
public class UserInfoInterceptor implements HandlerInterceptor {

    private final MicaRedisCache redisCache;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        if (StpUtil.isLogin()) {
            SecUser secUser = redisCache.hGet(RedisConstants.User.USER_INFO_ID, StpUtil.getLoginIdAsString());
            SecurityUtils.setUser(secUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        SecurityUtils.clear();
    }
}
